<script lang="ts" setup>
import { Search, Postcard } from '@element-plus/icons-vue';
import { compile, computed, ref } from 'vue';
import { ElMessage } from 'element-plus';
import http from '@/http';
import { el } from 'element-plus/es/locale';

//显示状态
const displayStatus = ref(false);
//搜索框的值
const regId = ref('');

//查询到患者病例信息
const caseInformation = ref({
  regId: '', //病例编号
  deptName: '', //科室名称
  careDate: '', //就诊时间
  caseResult: '', //诊断信息
  userName: '', //医生姓名
  patientName: '', //病人姓名
  caseTitle: '', //主诉
  doctorTips: '', //医生建议
  chId: ''
})

const chId = ref('')
const obtained = ref({
  coId: '',
  coType: ''
})

//需要传的参数
const coId = ref(0)
const coType = ref(0)


//查询
function query() {
  if (regId.value != '') {
    http.get('/hisCareHistory/obtainRegistrationInformation?id=' + regId.value)
      .then((res) => {
        if (res != '') {
          displayStatus.value = true;
          caseInformation.value = res;
          chId.value = res.chId;
          regId.value = '';
          //获取coId
          http.get('/hisCareOrde/getCoId?id=' + chId.value)
            .then((res) => {
              if (res != "") {
                obtained.value = res;
                console.log(obtained.value);
                obtained.value.forEach(item => {
                  const extractedInformation = {
                    co_id: item.coId,
                    co_type: item.coType,
                  };
                  coId.value = extractedInformation.co_id;
                  coType.value = extractedInformation.co_type;
                  if (extractedInformation.co_type == '0') {
                    //查询检查处方
                    http.get('/hco/getInspect?coId=' + coId.value)
                      .then((res) => {
                        if (res != '') {
                          checkPrescriptionTableData.value = res;
                          calculateTheTotalAmountForInspection();
                          console.log(checkPrescriptionTableData.value)
                        }
                      })
                  } else if (extractedInformation.co_type == '1') {
                    http.get('/hco/getMedicine?coId=' + coId.value)
                      .then((res) => {
                        if (res != '') {
                          drugPrescriptionTableData.value = res;
                          calculateTheTotalAmountOfDrugs();
                          console.log(drugPrescriptionTableData.value)
                        }
                      })
                  }
                });
              }
            })
        } else {
          displayStatus.value = false;
        }
      })
  } else {
    ElMessage({
      message: '请输入挂号单ID',
      type: 'error',
    })
  }

}
//读取IC卡
function readICCard() {
  ElMessage({
    message: '请刷卡',
    type: 'success',
  })
}

//折叠面板
const activeNames = ref(['1'])
const handleChange = (val: string[]) => {
  console.log(val)
}

//检查处方的金额
const checkPrescriptionAmount = ref(0);
//检查处方的数据
const checkPrescriptionTableData = ref([{}])


// 计算检查总金额的函数
function calculateTheTotalAmountForInspection() {
  let sum = 0;
  checkPrescriptionTableData.value.forEach(element => {
    if (element.price) {
      sum += parseFloat(element.price);
    }
  });
  checkPrescriptionAmount.value = sum;
}

//药品处方的金额
const drugPrescriptionAmount = ref(0)
//药品处方的数据
const drugPrescriptionTableData = ref([{}])

// 计算药品总金额的函数
function calculateTheTotalAmountOfDrugs() {
  let sum = 0;
  drugPrescriptionTableData.value.forEach(item => {
    if (item.price) {
      sum += parseFloat(item.price);
    }
  });
  drugPrescriptionAmount.value = sum;
}


//需支付的金额
const allAmount = computed(() => {
  return drugPrescriptionAmount.value + checkPrescriptionAmount.value;
})

//支付的弹窗
const paymentDialogBox = ref(false);

const refundInformation = ref({
  backAmount: 0,
  chId: '',
  regId: '',
  patientName: '',
  backStatus: 1,
})

function oneClickRefund(){
  paymentDialogBox.value = true;
}

//确认退费
function confirmPayment() {
  refundInformation.value.chId = chId.value;
  refundInformation.value.patientName = caseInformation.value.patientName;
  refundInformation.value.regId = caseInformation.value.regId;
  refundInformation.value.backAmount = allAmount.value;
  http.post('/hisOrderBackfee/addHisOrderBackfee',refundInformation.value)
    .then((res) => {
      if (res == 1) {
        ElMessage({
          message: '退费成功',
          type: 'success',
        })
      } else {
        ElMessage({
          message: '退费失败',
          type: 'error',
        })
      }
    })
  obtained.value.forEach(element => {
    const extractedInformation = {
      co_id: element.coId,
    };
    coId.value = extractedInformation.co_id;
    http.get('/hco/refund?coId=' + coId.value)
      .then((res) => {
        if (res == 1) {
          ElMessage({
            message: '退费成功',
            type: 'success',
          })
        }
      })
  });
  paymentDialogBox.value = false;
  displayStatus.value = false;
}
</script>
<template>
  <!-- 搜索框 -->
  <el-row>
    <el-col :span="8">
      <el-form-item label="挂号单ID">
        <el-input v-model="regId" type="text" autocomplete="off" placeholder="请输入挂号单" property="name" />
      </el-form-item>
    </el-col>
    <el-col :span="16">&nbsp;
      <el-button type="primary" :icon="Search" style="background-color: #1B8DFF;" @click="query">查询</el-button>
      <el-button type="primary" :icon="Search" style="background-color: #1B8DFF;" @click="readICCard">读取IC卡</el-button>
    </el-col>
  </el-row>

  <div v-if="displayStatus">
    <el-row>
      <el-col :span="4">
        <p><span>挂号单号：</span></p>
        <p><span>科室名称：</span></p>
        <p><span>就诊时间：</span></p>
        <p><span>诊断信息：</span></p>
      </el-col>
      <el-col :span="4">
        <p><span>{{ caseInformation.regId }}</span></p>
        <p><span>{{ caseInformation.deptName }}</span></p>
        <p><span>{{ caseInformation.careDate }}</span></p>
        <p><span>{{ caseInformation.caseResult }}</span></p>
      </el-col>
      <el-col :span="4">
        <div class="grid-content ep-bg-purple" />
      </el-col>
      <el-col :span="4">
        <div class="grid-content ep-bg-purple-light" />
      </el-col>
      <el-col :span="4">
        <p><span>医生姓名：</span></p>
        <p><span>患者姓名：</span></p>
        <p><span>主诉：</span></p>
        <p><span>医生建议：</span></p>
      </el-col>
      <el-col :span="4">
        <p><span>{{ caseInformation.userName }}</span></p>
        <p><span>{{ caseInformation.patientName }}</span></p>
        <p><span>{{ caseInformation.caseTitle }}</span></p>
        <p><span>{{ caseInformation.doctorTips }}</span></p>
      </el-col>
    </el-row>
    <el-button type="primary" :icon="Postcard" style="background-color: red;" @click="oneClickRefund">一键退费</el-button>
    <span>&nbsp;总费用：{{ allAmount }}</span>
    <br>
    <el-row>
      <el-col :span="24">
        <div class="demo-collapse">
          <el-collapse v-model="activeNames" @change="handleChange">
            <el-collapse-item :title="'【检查处方】【1】【处方金额】：￥' + checkPrescriptionAmount" name="1">
              <div>
                <el-table :data="checkPrescriptionTableData" border style="width: 100%" empty-text="暂无数据">
                  <el-table-column property="itemId" label="序号" align="center" />
                  <el-table-column property="itemName" label="项目名称" align="center" />
                  <el-table-column property="price" label="单价（元）" align="center" />
                  <el-table-column property="price" label="金额（元）" align="center" />
                  <el-table-column property="remark" label="检查备注" align="center" />
                </el-table>
              </div>
            </el-collapse-item>

            <el-collapse-item :title="'【药品处方】【2】【处方金额】：￥' + drugPrescriptionAmount" name="2">
              <div>
                <el-table :data="drugPrescriptionTableData" border style="width: 100%" empty-text="暂无数据">
                  <el-table-column property="itemId" label="序号" align="center" />
                  <el-table-column property="itemName" label="项目名称" align="center" />
                  <el-table-column property="price" label="单价（元）" align="center" />
                  <el-table-column property="price" label="金额（元）" align="center" />
                  <el-table-column property="remark" label="检查备注" align="center" />
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-col>
    </el-row>
  </div>

  <div style="width: 300px; margin: auto;" v-else>请输入正确的挂号单ID查询</div>

  <!-- 退费 -->
  <el-dialog v-model="paymentDialogBox" width="500" center>
    <el-row>
      <el-col :span="24">
        <p><span>费用</span> <span>{{ allAmount }}</span></p>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="paymentDialogBox = false">退出</el-button>
        <el-button type="primary" @click="confirmPayment">
          确认退费
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped></style>
